package com.example.faqdemo.controller;

import com.example.faqdemo.entity.FAQ;
import com.example.faqdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/faq")
public class FAQController {
    @Autowired
    private FAQService faqService;

    @Autowired
    private UserService userService;

    @GetMapping
    public List<FAQ> getAllFAQs(@RequestParam String userId) { // 修改为接收字符串类型的 userId
        User user = userService.findByUsername(userId);
        if (user != null) {
            return faqService.getAllFAQs();
        }
        return null;
    }

    @GetMapping("/{id}")
    public FAQ getFAQById(@PathVariable Integer id, @RequestParam String userId) { // 修改为接收字符串类型的 userId
        User user = userService.findByUsername(userId);
        if (user != null) {
            return faqService.getFAQById(id);
        }
        return null;
    }

    @PostMapping
    public FAQ createFAQ(@RequestBody FAQ faq, @RequestParam String userId) { // 修改为接收字符串类型的 userId
        User user = userService.findByUsername(userId);
        if (user != null && user.getType() == 1) {
            return faqService.saveFAQ(faq);
        }
        return null;
    }

    @PutMapping("/{id}")
    public FAQ updateFAQ(@PathVariable Integer id, @RequestBody FAQ faqDetails, @RequestParam String userId) { // 修改为接收字符串类型的 userId
        User user = userService.findByUsername(userId);
        if (user != null && user.getType() == 1) {
            FAQ faq = faqService.getFAQById(id);
            if (faq != null) {
                faq.setCategory(faqDetails.getCategory());
                faq.setQuestion(faqDetails.getQuestion());
                faq.setAnswer(faqDetails.getAnswer());
                return faqService.saveFAQ(faq);
            }
        }
        return null;
    }

    @DeleteMapping("/{id}")
    public String deleteFAQ(@PathVariable Integer id, @RequestParam String userId) { // 修改为接收字符串类型的 userId
        User user = userService.findByUsername(userId);
        if (user != null && user.getType() == 1) {
            faqService.deleteFAQ(id);
            return "FAQ deleted successfully";
        }
        return "Permission denied";
    }

    @GetMapping("/search")
    public List<FAQ> searchFAQs(@RequestParam String keyword, @RequestParam String userId) { // 修改为接收字符串类型的 userId
        User user = userService.findByUsername(userId);
        if (user != null) {
            return faqService.searchFAQs(keyword);
        }
        return null;
    }
}